package com.qing.expert.core.security;

import com.qing.expert.common.exception.BusinessException;
import com.qing.expert.common.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.annotation.Resource;

/**
 * 认证拦截器
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            throw new BusinessException(401, "未登录");
        }

        // 验证token
        if (!jwtUtils.validateToken(token)) {
            throw new BusinessException(401, "token已过期或无效");
        }

        // 将用户信息存入request
        request.setAttribute("userId", jwtUtils.getUserIdFromToken(token));
        request.setAttribute("role", jwtUtils.getRoleFromToken(token));

        return true;
    }

    public void validateAdminRole(HttpServletRequest request) {
        Integer role = (Integer) request.getAttribute("role");
        if (role == null || role != 1) { // 1代表管理员角色
            throw new BusinessException(403, "无权限访问");
        }
    }
}